package com.filestation.backend.service.impl;

import com.filestation.backend.config.TencentCosConfig;
import com.filestation.backend.service.CosService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
public class CosServiceImpl implements CosService {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private TencentCosConfig cosConfig;

    @Override
    public String uploadFile(MultipartFile file, String key) {
        try {
            // 设置元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            
            // 上传文件
            PutObjectRequest putRequest = new PutObjectRequest(
                    cosConfig.getBucketName(),
                    cosConfig.getUploadFolder() + key,
                    file.getInputStream(),
                    metadata
            );
            cosClient.putObject(putRequest);
            
            // 返回访问URL
            return getFileUrl(key);
        } catch (IOException e) {
            log.error("上传文件到腾讯云COS失败", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteFile(String key) {
        try {
            cosClient.deleteObject(cosConfig.getBucketName(), cosConfig.getUploadFolder() + key);
            return true;
        } catch (Exception e) {
            log.error("从腾讯云COS删除文件失败", e);
            return false;
        }
    }

    @Override
    public String getFileUrl(String key) {
        return cosConfig.getBaseUrl() + "/" + cosConfig.getUploadFolder() + key;
    }

    @Override
    public String uploadFile(InputStream inputStream, long size, String contentType, String key) {
        try {
            // 设置元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(size);
            metadata.setContentType(contentType);
            
            // 上传文件
            PutObjectRequest putRequest = new PutObjectRequest(
                    cosConfig.getBucketName(),
                    cosConfig.getUploadFolder() + key,
                    inputStream,
                    metadata
            );
            cosClient.putObject(putRequest);
            
            // 返回访问URL
            return getFileUrl(key);
        } catch (Exception e) {
            log.error("上传文件到腾讯云COS失败", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        }
    }
} 